package com.lijiayue.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lijiayue.aliyun.AliOssProperties;
import com.lijiayue.mapper.StudentMapper;
import com.lijiayue.model.domain.Student;
import com.lijiayue.service.StudentService;
import com.lijiayue.util.AuthContextHolder;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService  {

    @Resource
    private AliOssProperties aliOssProperties;

    /**
     * 文件上传
     *
     * @param extension   文件拓展名
     * @param inputStream 文件流
     * @return 文件访问路径
     */
    @Override
    public String upload(String extension, InputStream inputStream) {
        String fileName = UUID.randomUUID() + extension;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliOssProperties.getEndpoint(), aliOssProperties.getAccessKeyId(), aliOssProperties.getAccessKeySecret());
        StringBuilder stringBuilder = new StringBuilder("https://");

        try {
            // 创建PutObject请求。
            ossClient.putObject(aliOssProperties.getBucketName(), fileName, inputStream);

            //文件访问路径规则 https://BucketName.Endpoint/ObjectName
            stringBuilder.append(aliOssProperties.getBucketName())
                    .append(".")
                    .append(aliOssProperties.getEndpoint())
                    .append("/")
                    .append(fileName);
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message");
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message");
        } finally {
            if (ObjectUtil.isNotEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }
        String url = stringBuilder.toString();
        Long userId = AuthContextHolder.getUserId();
        Student student = this.getById(userId);
        student.setAvatar(url);
        this.updateById(student);

        return stringBuilder.toString();
    }
}
